var ctx=window.daijia.ctx;
var jgpt=window.jgpt;
var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数

var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载

var search_name=null;
var search_phone=null;
var search_carNumber=null;
var search_gradeId=[];
var search_startTime=null;
var search_endTime=null;
var search_type=[];
var search_companyIds=[];
var search_permission=[];
var search_isPlatform=[];
var search_introduceName=null;

var upload_member = [];

var isUpPlatformInfo = window.isUpPlatformInfo;

$(function(){
    $("#startTime").val("");
    $("#endTime").val("");
    $("#startTime").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
    $("#endTime").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
    initdata(false);

    $('#companyIds').multiselect({
        enableFiltering: true,
        includeSelectAllOption: true,
        selectAllText: '全部',
        selectAllJustVisible: true,
        maxHeight:300,
        buttonWidth: '70%',
        nonSelectedText: '请选择所属公司',
        nSelectedText: ' - 已选择',
        numberDisplayed: 4,
        allSelectedText: '已选择全部'
    });

    //高级搜索
    $(".query-jiant").click(function(){
        var src=$("#jiant").attr("src");
        if(src.indexOf("jiant2")>=0){
            $("#jiant").attr("src",ctx+"/assets/img/jiant.png");
            $(".choose").slideDown(300);
        }else{
            $("#jiant").attr("src",ctx+"/assets/img/jiant2.png");
            $(".choose").slideUp(300);
        }
    });

    $("#searchButton").click(function(){

        var DATE_FORMAT = /^[0-9]{4}-[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1}$/;
        if($("#startTime").val()!=""){
            if(!DATE_FORMAT.test($("#startTime").val())){
                $.scojs_message("您输入的启始日期格式有误，正确格式如：2012-01-01", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if($("#endTime").val()!=""){
            if(!DATE_FORMAT.test($("#endTime").val())){
                $.scojs_message("您输入的结束日期格式有误，正确格式如：2012-01-01", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if($("#startTime").val()!="" && $("#endTime").val()!=""){
            if($("#startTime").val()>$("#endTime").val()){
                $.scojs_message("启始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }

        if(null!=$("#companyIds").val()){
            search_companyIds=$("#companyIds").val().join(",");
        }
        else{
            search_companyIds=[];
        }

        search_startTime=$("#startTime").val();
        search_endTime=$("#endTime").val();
        search_phone=$("#phone").val();
        search_carNumber=$("#carNumber").val();
        search_name=$("#name").val();
        if($("input[name=permission]:checked").length>0){
            search_permission=$("input[name=permission]:checked").val();
        }
        var permissionArr=[];
        $("input[name=permission]:checked").each(function(index,element){
            permissionArr.push($(element).val());
        });
        if(null!=permissionArr && permissionArr.length>0){
            search_permission=permissionArr.join(",");
        }
        else{
            search_permission=[];
        }
        
        var isPlatformArr=[];
		$("input[name=isPlatform]:checked").each(function(index,element){
			isPlatformArr.push($(element).val());
		});
		if(null!=isPlatformArr && isPlatformArr.length>0){
			search_isPlatform=isPlatformArr.join(",");
		}
		else{
			search_isPlatform=[];
		}

		search_introduceName = $("#introduceName").val();


        var typeArr=[];
        $("input[name=type]:checked").each(function(index,element){
            typeArr.push($(element).val());
        });
        if(null!=typeArr && typeArr.length>0){
            search_type=typeArr.join(",");
        }
        else{
            search_type=[];
        }

        var gradeArr=[];
        $("input[name=gradeId]:checked").each(function(index,element){
            gradeArr.push($(element).val());
        });
        if(null!=gradeArr && gradeArr.length>0){
            search_gradeId=gradeArr.join(",");
        }
        else{
            search_gradeId=[];
        }

        offset=0;
        initdata(false);

    });
    //滚动
//	$(window).scroll(function () {
//        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
//        //$(window).height()获取当前窗体的高度
//        //$(document).height()获取当前文档的高度
//        var bot = 0; //bot是底部距离的高度
//        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
//        	if(pageLoading){
//        		pageLoading=false;
//        		offset+=limit;
//        		initdata(true);
//        	}
//        }
//    });

    $("#export_button").click(function(){

        window.location=ctx+"/member/exportOrder?"+"&type="+search_type+
            "&gradeId="+search_gradeId+"&companyIds="+search_companyIds+
            "&permission="+search_permission+"&isPlatform="+search_isPlatform+"&phone="+$("#phone").val()+"&name="+$("#name").val()
            +"&carNumber="+$("#carNumber").val()+"&startTime="+$("#startTime").val()+"&endTime="+$("#endTime").val() + "&introduceName="+$("#introduceName").val();
    });


    $(document).on("keydown","body",function(){
        if(window.event.keyCode == 13){
            $("#searchButton").click();
        }
    });
    $(document).on("click",".feedback",function(){
        window.open(ctx+'/phonevisit/memberadd/'+$(this).attr("data-val"), '_blank', 'height=650,width=1024,scrollbars=yes,resizable=yes,alwaysRaised=yes,toolbar=no');
    });



    $(document).on("click",".checkMemberItem",function(event){
        var flag = $(this).attr("flag");
        console.log(flag);
        if(Boolean.parse(flag)){
            $(this).attr("flag",false);
            upload_member.remove(parseInt($(this).val()));
        }else{
            $(this).attr("flag",true);
            upload_member.push(parseInt($(this).val()));
        }
        $(".checkItemInfoLable").remove();
        $(".query-jiant").append("<span class='label label-info checkItemInfoLable' style='position: absolute;right: 80px;margin-top: 10px;'>共选中 : "+upload_member.length+"条</span>");
        event.stopPropagation();
    });


    var getCheckMemeberInfo;
    $("#upload_button").click(function(){
    	
    	if(isUpPlatformInfo != "true"){
    		 $.scojs_message("监管平台上传开关已关闭", $.scojs_message.TYPE_ERROR);
    		 return;
    	}
    	
        $("#loadingPro").width(10);
		/*var item =  $(".checkDriverItem[flag=true]");
		 var ids =[];
		 for(var i= 0,id;id=item[i++];){
		 ids.push($(id).val());
		 }*/
        if(upload_member.length==0){
            $.scojs_message("请选择需要上报的客户", $.scojs_message.TYPE_ERROR);
            return false;
        }

        $(".tempInfoStr").remove();
        $(".finish_info").remove();
        $("#progressDiv").show();
        $("#uploadMemberModal .modal-dialog").addClass("modal-sm");
        $("#uploadMemberModal").modal();
        getCheckMemeberInfo = window.setInterval(function(){
            var temp = $("#progressDiv").width();
            var load = $("#loadingPro").width();
            if(load>=temp){
                $("#loadingPro").width(10);
            }else{
                $("#loadingPro").width(load+10);
            }
        },100);

        var param = upload_member.join(",")
        $.post(ctx+"/member/checkMember",{ids:param},function(data){
            if(data.success){
                var temp = window.setInterval(function(){
                    $.get(ctx+"/member/getCheckMemberInfo",{},function(result){
                        if(result.isEnd){
                            clearInterval(getCheckMemeberInfo);
                            clearInterval(temp);
                            var total=0;
                            var index=0;
                            var infoStr="<div class='tempInfoStr'>";
                            for(var key in result){
                                if(key != "isEnd"){
                                    infoStr+=(++index)+": 【"+key+"】"+result[key]+"<br/>";
                                    total++;
                                }
                            }
                            infoStr+="</div>";
                            if(total==0){
                                $("#progressDiv").hide();
                                $("#uploadMemberModal .modal-body").append("<span class='finish_info'>数据校验通过，是否上传？&nbsp<button type='button' id='uploadMemberInfoButton' class='btn btn-info btn-sm' style='padding:2px 10px;''>上传</button></span>");
                            }else{
                                $("#uploadMemberModal .modal-dialog").removeClass("modal-sm");
                                $("#uploadMemberModal .modal-body").append(str)
                            }
                        }
                    });
                },1000);
            }

        });


    });

    $(document).on("click","#uploadMemberInfoButton",function(){
        if(upload_member.length==0){
            $.scojs_message("请选择需要上报的乘客", $.scojs_message.TYPE_ERROR);
            return false;
        }
        var params = upload_member.join(",")
        $.post(ctx+"/member/uploadMember",{ids:params},function(data){
            //$(".finish_info").hide();
            if(data.success){
                if(data.success){
                    if(data.platform=="XmPlatform" || data.platform=="QdZhongZhiPlatform"){
                        $.scojs_message("上报成功", $.scojs_message.TYPE_OK);
                        $("#uploadMemberModal").modal("hide");
                    }
                    else{
                        $.scojs_message("上传成功:"+data.successNum+"条,失败:"+data.failNum+"条", $.scojs_message.TYPE_OK);
                        $("#uploadMemberModal").modal("hide");
                    }
                }else{
                    $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                }
            }else{
                $.scojs_message("上传失败", $.scojs_message.TYPE_ERROR);
            }
            var s = window.setInterval(function(){
            	window.location.href = ctx+"/member/list";
            }, 1000);
        });
    })



    $("#all").click(function(event){
        var flag = Boolean.parse($("#all").attr("val"));
        if (flag) {
            $(this).attr("val", false);
            var items = $(".checkMemberItem");
            for(var i= 0,val;val=items[i++];){
                $(val).removeAttr("checked");
                $(val).attr("flag",false);
                upload_member.remove(parseInt($(val).val()));
            }
        } else {
            $(this).attr("val", true);
            var items = $(".checkMemberItem");
            for(var i= 0,val;val=items[i++];){
                $(val).prop("checked","true");
                $(val).attr("flag",true);
                upload_member.remove(parseInt($(val).val()));
                upload_member.push(parseInt($(val).val()));
            }
        }
        console.debug(upload_member);
        $(".query-jiant").append("<span class='label label-info checkItemInfoLable' style='position: absolute;right: 80px;margin-top: 10px;'>共选中 : "+upload_member.length+"条</span>");
        event.stopPropagation();
    });


});



function initdata(isappend){

    $.ajax({
        url : ctx+'/member/listData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
            "type":search_type,
            "gradeId":search_gradeId,
            "companyIds":search_companyIds,
            "startTime":search_startTime,
            "endTime":search_endTime,
            "phone":search_phone,
            "carNumber":search_carNumber,
            "name":search_name,
            "permission":search_permission,
            "isPlatform":search_isPlatform,
            "pager.offset":offset,
            "limit":limit,
            "introduceName":search_introduceName
        },
        success : function(result){
            $("#all").attr("val","false");
            $("#all").removeAttr("checked");
            var newcontent = '';
            var totalElements=result.totalElements;
            if(totalElements>0){
                $(result.content).each(function(index,data){
                	
                    var mainButton="";
                    var selectButton="";

                    mainButton="<a href="+ctx+"/member/editPersonal/"+data.id+" type='button' class='btn btn-primary btn-xs'>编辑</a>";
                    if(memberedit){
                        selectButton+="<li><a href='javascript:;' data-value="+data.id+"  class='btn-link deletethis'>删除</a></li>";
                    }
                    if(membermoneyview){
                        if(data.type==0){
                            selectButton+="<li><a href="+ctx+"/member/money/"+data.id+" class='btn-link'>账户明细</a></li>";
                        }
                    }
                    selectButton+="<li><a href="+ctx+"/member/couponlist/"+data.id+" class='btn-link'>查看优惠劵</a></li>";
                    if(phonevisit){
                        selectButton+="<li><a href="+ctx+"/phonevisit/memberRecord/"+data.id+" class='btn-link'>回访记录</a></li>";
                    }
                    if(phonevisit){
                        selectButton+="<li><a href='javascript:;' class='btn-link feedback' data-val="+data.id+">回访</a></li>";
                    }
                    if(memberedit){
                        if(!data.inBlackList){
                            selectButton+="<li><li><a href='javascript:;' data-value="+data.id+"  class='btn-link blackthis'>添加到黑名单</a></li></li>"
                        }
                    }
                    selectButton+="<li><a href="+ctx+"/member/findUsuallyEmploy/"+data.id+" class='btn-link'>查看收藏司机</a></li>";
                    var allButton="<div class='btn-group'>"+
                        mainButton+
                        "<button type='button' class='btn "+"btn-primary"+" btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>"+
                        "<span class='caret'></span>"+
                        "<span class='sr-only'>Toggle Dropdown</span>"+
                        "</button>"+
                        "<ul class='dropdown-menu' role='menu'>"+
                        selectButton+
                        "</ul>"+
                        "</div>";

                    var drawMoney ="";
                    if(data.type==0){
                        if(data.drawMoney!=null){
                            drawMoney=data.drawMoney;
                        }else{
                            drawMoney="0";
                        }
                    }else if(data.type==1){
                        drawMoney="-";
                    }

                    var nodrawMoney ="";
                    if(data.type==0){
                        if(data.nodrawMoney!=null){
                            nodrawMoney=data.nodrawMoney;
                        }else{
                            nodrawMoney="0";
                        }
                    }else if(data.type==1){
                        nodrawMoney="-";
                    }

                    var introducer=data.introducer;
                    if(data.introducer!=null&&data.introducer.length>0){
                        if(data.introduceType==0){
                            introducer+="(客户推荐)";
                        }else if(data.introduceType==1){
                            introducer+="(服务人员推荐)";
                        }
                    }
                    var checkFlag = false;
                    for(var i= 0;val=upload_member[i++];){
                        if(val == data.id){
                            checkFlag = true;
                        }
                    }
                    
                    var upStatus = "";
                    if(data.upStatus == 1){
                    	upStatus = "√";
                    }
                    
                    var checkString = "";
                    var upStatusString = "";
                    if(jgpt){
                    	checkString =  
                    		"<td>" +
                    			"<div class='checkbox checkbox-success '  style='margin-top:-5px;margin-left:30px;'>"+
                    				"<input id='"+data.id+"' class='styled checkMemberItem' flag='"+(checkFlag?"true":"false")+"' "+(checkFlag?"checked":"")+" value='"+data.id+"' type='checkbox' />"+
                    				"<label for='"+data.id+"'></label>"+
                    			"</div>" +
                    		"</td>"
                    	upStatusString = "<td style='text-align: center'>"+upStatus+"</td>";
                    }
                    
                    newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
                    	checkString+
                        "<td>"+data.name +(data.inBlackList?"&nbsp;<span class='label label-danger status-td' style='background-color: #101010;'>黑</span>":"")+"</td>"+
                        upStatusString+
                        "<td>"+(data.idCardPhoto==null?"<span style='color:red;'>否</span>":"是")+"</td>"+
                        "<td>"+(data.enterprise_name==null?"-":data.enterprise_name)+"</td>"+
                        "<td>"+data.channel_name+"</td>"+
                        "<td>"+data.phone+"</td>"+
                        "<td>"+(data.allowOverdraw?"<span style='color:red;'>是</span>":"否")+"</td>"+
                        "<td><span style='color:#ff950b;'>"+drawMoney+"</span></td>"+
                        "<td><span style='color:#ff950b;'>"+nodrawMoney+"</span></td>"+
                        (ismain ?"<td>"+data.companyName+"</td>":"")+
                        "<td>"+data.grade_name+"</td>"+
                        "<td>"+(data.plateNumber==null?"-":data.plateNumber)+"</td>"+
                        "<td>"+(introducer==null?"-":introducer)+"</td>"+
                        "<td>"+data.created+"</td>"+
                        "<td>"+allButton+"</td>"+
                        "</tr>";
                });
            }
            else{
                $("#NoData").text("当前页面暂无记录 ");
            }


//        	hideLoading();

            if(!isappend){
                $(".table tbody .grid-data").remove();
            }
            $(".table tbody").append(newcontent);

            $(".table tbody .grid-data").each(function(index,element){
                $(element).fadeIn(200+(index*35));
            });

            if(!hasShowPages){
                if(!isappend){
                    currentTotalElements=result.numberOfElements;
                    pageLoading=true;
                }
                else{
                    if(currentTotalElements<totalElements){
                        currentTotalElements+=result.numberOfElements;
                        pageLoading=true;
                    }
                    else{
                        pageLoading=false;
                    }
                }
            }

            if(hasShowPages){
                firstLoadPages=true;
                $(".pageshow li a").html("共"+totalElements+" 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    page:(offset/limit)+1,
                    onSelect: function (page) {
                        limit=pagingLimit;
                        offset=(page-1)*limit;
                        if(!firstLoadPages){
                            initdata(false);
                        }
                        firstLoadPages=false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });

            }
            else{
                //滚动达到pagingLimit条开始显示分页
//        		if(currentTotalElements==pagingLimit){

                pageLoading=false;
                hasShowPages=true;

                $(".pageshow").show();
                $(".pagedata").show();
                $(".pageshow li a").html("共"+totalElements+" 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    onSelect: function (page) {
                        limit=pagingLimit;
                        offset=(page-1)*limit;
                        if(!firstLoadPages){
                            initdata(false);
                        }
                        firstLoadPages=false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });

//            	}
            }

        }
    });



    $(".importMember").click(function(){
        $("#importMemberModal").modal();
    });

    $("#memberExcel").fileinput({
        uploadUrl: ctx+'/member/importMember', // you must set a valid URL here else you will get an error
        allowedFileExtensions : ['xls', 'xlsx'],
        overwriteInitial: false,
        dropZoneEnabled:false,
        maxFileSize: 1024*10,
        maxFilesNum: 1,
        language: 'zh',
        dropZoneTitle:"拖拽文件到这里...",
        maxFileCount: 1, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        fileActionSettings:{
            indicatorNewTitle:'',
            indicatorNew:""
        },
        allowedPreviewTypes: ['image'],
        slugCallback: function(filename) {
            return filename.replace('(', '_').replace(']', '_');
        }
    }).on("fileuploaded", function(event, data) {
        $("#membermessageInfo").remove();
        var  resp = data.response;
        var str = "<div id='membermessageInfo' style='margin:-10px 0px 5px 0;word-break:break-all;'";
        if(resp.success){
            str += " class='alert alert-success'>";
            str +="导入完成:成功导入"+resp.rows+"条";
            if(resp.phoneCount != undefined && resp.phoneCount >0){
                str+=",电话号码重复:"+resp.phoneCount+"条";
            }
            $("#searchButton").click();
        }else{
            str += "class='alert alert-danger'>";
            if(resp.msg != undefined){
                str +=resp.msg;
                console.debug(resp.rowNum);
            }
            if(resp.phoneIndexs!=undefined &&resp.phoneIndexs.length>0){
                str += "在第["+resp.phoneIndexs.join(",")+"]行记录,电话号码格式错误!   <br/>";

            }
            if(resp.repeatPhone != undefined){
                var tempStr="";
                for(var key in resp.repeatPhone){
                    tempStr += "["+key+"行,"+resp.repeatPhone[key]+"行],";
                }
                console.debug(resp.repeatPhone);
                tempStr = tempStr.substr(0,tempStr.length-1);
                str += "在第 "+tempStr+"记录,电话号码重复!";
            }
        }
        str +="</div>";
        $(".kv-upload-progress").after(str);

    });

    $("#memberExcel").on("filecleared",function(event, data, previewId, index){
        $("#membermessageInfo").remove();
    });

    $("#importMemberModal .close").click(function(){
        $("#membermessageInfo").remove();
    });


    $("#downloadTemplet").click(function(){
        var url = $(this).attr("url");
        var downloadFrame = $('#downloadFrame');
        if(downloadFrame.length == 0){
            downloadFrame = $('<iframe id="downloadFrame" src="" style="display:none"></iframe>');
            $('body').append(downloadFrame);
        }
        downloadFrame.attr('src',ctx+url);

    });

}

Array.prototype.remove=function(val) {
    if(val == null ){
        return false;
    }
    var flag = false;
    for(var i=0,n=0;i<this.length;i++) {
        if(this[i] != val) {
            this[n++]=this[i];
        }else{
            flag = true;
        }
    }
    if(flag){
        this.length-=1;
    }
}

Boolean.parse = function (str) {
    switch (str.toLowerCase ()) {
        case "true":
            return true;
        case "false":
            return false;
        default:
            throw new Error ("Boolean.parse: Cannot convert string to boolean.");
    }
};
